package wangjg.codec.bitmap;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * 
 * @author wangjigang1
 *
 */
public class BitmapReader {
	private FileHeader fileHeader;
	private InfoHeader infoHeader;
	private String path;
	
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}
	
	public void read() {
		FileInputStream fis=null;
		try {
			fis=new FileInputStream(path);
			byte[] buf = new byte[54];
			fis.read(buf);
			ByteBuffer bb = ByteBuffer.wrap(buf);
			bb.order(ByteOrder.LITTLE_ENDIAN);
			this.readFileHeader(bb);
			this.readInfoHeader(bb);
			this.readPixelData(fis);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try{
				if(fis!=null)fis.close();
			}catch(Exception e){}
		}
	}
	
	private void readFileHeader(ByteBuffer bb) throws IOException{
		fileHeader = new FileHeader();
		fileHeader.setType(bb.getShort());
		fileHeader.setSize(bb.getInt());
		fileHeader.setReserved1(bb.getShort());
		fileHeader.setReserved2(bb.getShort());
		fileHeader.setOffset(bb.getInt());
	}
	

	private void readInfoHeader(ByteBuffer bb){
		infoHeader = new InfoHeader();
		infoHeader.setSize(bb.getInt());
		infoHeader.setWidth(bb.getInt());
		infoHeader.setHeight(bb.getInt());
		infoHeader.setPlanes(bb.getShort());
		infoHeader.setBits(bb.getShort());
		infoHeader.setCompression(bb.getInt());
		infoHeader.setImagesize(bb.getInt());
		infoHeader.setXresolution(bb.getInt());
		infoHeader.setYresolution(bb.getInt());
		infoHeader.setNcolours(bb.getInt());
		infoHeader.setImportantcolours(bb.getInt());
	}
	
	private void readPixelData(InputStream is) throws IOException{
		int size = this.infoHeader.getImagesize();
		byte[] buf = new byte[size];
		is.read(buf);
	}

	public static void main(String[] args) throws IOException {
		BitmapReader br = new BitmapReader();
		br.setPath("D:\\1px.bmp");
		br.read();
	}
}
